package cc.yiueil.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) throws Exception {
        AddThread add = new AddThread();
        DecThread dec = new DecThread();
        add.start();
        dec.start();
        add.join();
        dec.join();
        System.out.println(Counter.count);
    }
}
class Counter {
    public static final Lock LOCK = new ReentrantLock();
    public static int count = 0;
}
class AddThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            try {
                if (Counter.LOCK.tryLock(0, TimeUnit.SECONDS)) {
                    try {
                        Counter.count += 1;
                    } finally {
                        Counter.LOCK.unlock();
                    }
                } else {
                    // 如果在设定的时间内没有获取到锁, 可以在这里处理超时情况, 避免死锁
                    System.out.println("timed out waiting for lock");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class DecThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            Counter.LOCK.lock();
            try {
                Counter.count -= 1;
            } finally {
                Counter.LOCK.unlock();
            }
        }
    }
}